<script setup>
import dayjs from 'dayjs';
import { find, merge } from 'lodash-es';
import { useRoute } from '@/router/index.js';
import { useRequest } from '@/hooks/requestHooks.js';
import { dateFormat } from '@/utils/index.js';
import { getAlarmCalendar, getAreaList, getBuildingByArea } from '@/api/index.js';
const themeToggleStyle = {
  'theme-dark': {
    curMth: {
      color: '#f5f5f5',
      backgroundColor: '#161e35',
    },
    notCurMth: {
      color: '#545864',
      backgroundColor: '#202637',
      // border: '1px solid #232e4a',
    },
  },
  'theme-light': {
    curMth: {
      // color: '#fff',
      // backgroundColor: '#1fa3d2',
      // border: '1px solid #74a3b4',
    },
    notCurMth: {
      color: 'rgba(255,255,255,0.8)',
      backgroundColor: '#c1c1c1',
      // border: '1px solid #a5a5a5',
    },
  },
};
const curMthStyle = (theme, data) => {
  const todayBg = {};
  if (data.isSelected) todayBg.backgroundColor = '#f58819';
  return merge({ position: 'relative' }, themeToggleStyle[theme].curMth, todayBg);
};

const route = useRoute();
const queryForm = ref(null);
const queryParams = ref({
  alarmType: route.query?.alarmType ?? null,
  enterpriseCode: route.query?.buildingCode ?? null,
});
const month = ref(dayjs().toDate());
const selectDay = ref(dayjs().format('YYYY-MM-DD'));
const alarmList = ref([]);
const cascader = ref();
const cascaderProps = ref({
  emitPath: true,
  checkStrictly: true,
  label: 'areaName',
  value: 'areaName',
});

const [calendarList, loading, runCalendar] = useRequest(getAlarmCalendar, {
  defaultParams: [{ month: dateFormat(month.value, 'YYYY-MM') }],
  onSuccess: res => {
    alarmList.value = find(res.data, v => v.date === selectDay.value).alarmList;
  },
});
const [areaList] = useRequest(getAreaList, { defaultParams: [{}] });
const insParams = ref({
  isStage: '1',
  areaName: null,
});
const [institutionList, , run] = useRequest(getBuildingByArea, {
  defaultParams: [insParams.value],
});

const handleDayClick = day => {
  selectDay.value = day;
  alarmList.value = find(calendarList.value, v => v.date === day).alarmList;
};
const addMonth = () => {
  month.value = dayjs(month.value).add(1, 'month').toDate();
  runCalendar({ month: dateFormat(month.value, 'YYYY-MM'), ...queryParams.value });
};
const subtractMonth = () => {
  month.value = dayjs(month.value).subtract(1, 'month').toDate();
  runCalendar({ month: dateFormat(month.value, 'YYYY-MM'), ...queryParams.value });
};
const handleAlarmType = val => {
  runCalendar({ month: dateFormat(month.value, 'YYYY-MM'), ...queryParams.value });
};
const cascaderChange = bool => {
  if (!bool) {
    const areaName = cascader.value.join('/');
    insParams.value.areaName = areaName;
    run(insParams.value);
  }
};
const selectChange = () => {
  runCalendar({ month: dateFormat(month.value, 'YYYY-MM'), ...queryParams.value });
};
const ECAlarmTextDisplay = type => {
  switch (type) {
    case '基准':
      return { energyBasis: '能耗基准', energyExceeding: '超出基准' };
    case '引导':
      return { energyBasis: '引导值', energyExceeding: '超出引导值' };
    case '上限':
      return { energyBasis: '约束值', energyExceeding: '超出约束值' };
  }
};
</script>

<template>
  <div class="app-container u-df-st">
    <div class="u-h100 u-base-fg calendar-left">
      <ul class="sbfx-calendar-header u-prim-text u-base-fg u-df-spb">
        <li class="u-mr30 u-df-st u-fs20">
          <i class="el-icon-caret-left" style="color: #9196a2" @click="subtractMonth"></i>
          <span class="u-mlr10">{{ dateFormat(month, 'YYYY年') }}</span>
          <span class="u-primary u-mr10">{{ dateFormat(month, 'MM月') }}</span>
          <i class="el-icon-caret-right" style="color: #9196a2" @click="addMonth"></i>
        </li>
        <li class="u-mr30 u-df-spb u-fs14">
          <div class="u-df-st u-mr20">
            <div class="calendar-legend"></div>
            能耗告警
          </div>
          <div class="u-df-st">
            <div class="calendar-legend u-bg-blue"></div>
            设备告警
          </div>
        </li>
      </ul>
      <div class="sbfx-calendar" :class="$store.state.global.setting.sideTheme">
        <el-calendar v-model="month" v-loading="loading">
          <template slot="dateCell" slot-scope="{ data }">
            <div
              v-if="data.type === 'current-month'"
              class="u-h100 u-df-ct u-fd-col"
              :style="curMthStyle($store.state.global.setting.sideTheme, data)"
              @click="handleDayClick(data.day)"
            >
              <div class="u-fw-b text-center">{{ dateFormat(data.day, 'D') }}</div>
              <div class="u-df-ct u-poa">
                <div
                  v-show="calendarList?.[dateFormat(data.day, 'D') - 1]?.hasEnergy"
                  class="calendar-legend u-mr0"
                ></div>
                <div
                  v-show="
                    calendarList?.[dateFormat(data.day, 'D') - 1]?.hasEnergy &&
                    calendarList?.[dateFormat(data.day, 'D') - 1]?.hasFacility
                  "
                  style="width: 8px"
                ></div>
                <div
                  v-show="calendarList?.[dateFormat(data.day, 'D') - 1]?.hasFacility"
                  class="calendar-legend u-mr0 u-bg-blue"
                ></div>
              </div>
            </div>
            <div
              v-else
              class="u-df-ct u-h100"
              :style="themeToggleStyle[$store.state.global.setting.sideTheme].notCurMth"
            >
              {{ dateFormat(data.day, 'D') }}
            </div>
          </template>
        </el-calendar>
      </div>
    </div>
    <div class="u-h100 u-base-fg calendar-right">
      <el-form
        ref="queryForm"
        :model="queryParams"
        label-width="80px"
        class="u-p20 u-w100"
        style="padding-bottom: 10px"
      >
        <el-form-item label="告警类型" prop="alarmType">
          <el-select
            v-model="queryParams.alarmType"
            placeholder="请选择告警类型"
            clearable
            size="small"
            class="u-w100"
            @change="handleAlarmType"
          >
            <el-option label="能耗告警" value="ENERGY"></el-option>
            <el-option label="设备告警" value="FACILITY"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行政区划">
          <el-cascader
            v-model="cascader"
            :props="cascaderProps"
            :options="areaList"
            placeholder="请选择行政区划"
            size="small"
            class="u-w100"
            clearable
            @visible-change="cascaderChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item prop="enterpriseCode" label="机构名称">
          <el-select
            v-model="queryParams.enterpriseCode"
            placeholder="请输入机构名称"
            filterable
            size="small"
            class="u-w100"
            clearable
            @change="selectChange"
          >
            <el-option
              v-for="(val, index) in institutionList"
              :key="`${val.enterpriseCode}-${index}`"
              :label="val.enterpriseName"
              :value="val.enterpriseCode"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="u-divider-bg" style="height: 1px"></div>
      <div class="u-p20" style="height: calc(100% - 183px)">
        <el-timeline v-show="alarmList.length > 0" class="calendar-timeline">
          <el-timeline-item
            v-for="(item, idx) in alarmList"
            :key="`${item.alarmCode}-${idx}`"
            :timestamp="`${item.startTimeStr}（推送时间）`"
            :color="item.alarmType === '能耗告警' ? '#e62b2b' : '#196be6'"
            placement="top"
          >
            <div v-if="item.alarmType === '能耗告警'" class="ECAlarm-wrapper u-p20">
              <div class="u-fs14 u-fw-b u-mb5">
                {{ item.enterpriseName }}用{{ item.energyType }}{{ item.alarmType }}提醒
              </div>
              <span class="u-fs12" style="color: rgba(0, 0, 0, 0.4)">{{ item.dataDate }}</span>
              <el-divider></el-divider>
              <ul class="u-df-st">
                <li>
                  <div :title="item?.energyBasis">{{ item?.energyBasis }}</div>
                  <div>{{ ECAlarmTextDisplay(item.checkType)?.energyBasis ?? '-' }}</div>
                </li>
                <li>
                  <div :title="item.energyValue">{{ item.energyValue }}</div>
                  <div>实际能耗</div>
                </li>
                <li>
                  <div :title="item?.energyExceeding">{{ item?.energyExceeding }}</div>
                  <div>{{ ECAlarmTextDisplay(item.checkType)?.energyExceeding ?? '-' }}</div>
                </li>
              </ul>
            </div>
            <div v-else class="equAlarm-wrapper u-p20">
              <div class="u-fs14 u-fw-b u-mb5">{{ item.enterpriseName }}{{ item.alarmType }}提醒</div>
              <span class="u-fs12" style="color: rgba(0, 0, 0, 0.4)">{{ item.dataDate }}</span>
              <el-divider></el-divider>
              <ul class="u-df-st">
                <li>
                  <div :title="item.equName">{{ item.equName }}</div>
                  <div>设备名称</div>
                </li>
                <li>
                  <div :title="item.alarmReason">{{ item.alarmReason }}</div>
                  <div>告警原因</div>
                </li>
              </ul>
            </div>
          </el-timeline-item>
        </el-timeline>
        <div v-show="alarmList?.length <= 0" class="u-df-ct u-fs14 u-sec-text">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.calendar-left {
  width: 75%;
  margin-right: 20px;
}
.calendar-right {
  width: calc(25% - 20px);
  overflow-y: auto;
}
.calendar-legend {
  width: 10px;
  height: 10px;
  margin-right: 5px;
  border-radius: 50%;
  background-color: #e62b2b;
}
.calendar-timeline {
  height: 100%;
  padding: 10px 0;
  overflow-y: auto;
  overflow-y: overlay;
  scrollbar-width: none;
  ::-webkit-scrollbar {
    width: 0px;
    display: none; /* Chrome Safari */
  }
}
.ECAlarm-wrapper {
  background-color: #fbe8e8;
  border-radius: 4px;
  > ul {
    > li {
      flex: 1;
      color: #e62b2b;
      font-size: 12px;
      text-align: center;
      > div:first-of-type {
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: bold;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
.equAlarm-wrapper {
  background-color: #e0e7f1;
  border-radius: 4px;
  > ul {
    > li {
      flex: 1;
      color: #196be6;
      font-size: 12px;
      > div:first-of-type {
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: bold;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
.u-poa {
  position: absolute;
  bottom: 20%;
  left: 50%;
  transform: translateX(-50%);
}
.u-bg-blue {
  background-color: #196be6;
}
.u-mr0 {
  margin-right: 0;
}
:deep(.el-form-item) {
  margin-bottom: 10px;
}
:deep(.el-form-item__content) {
  width: calc(100% - 80px);
}
:deep(.el-timeline-item__node--normal) {
  left: 0;
}
:deep(.el-timeline-item__tail) {
  left: 5.5px;
  border-left-width: 1px;
}
.sbfx-calendar {
  width: 100%;
  height: calc(100% - 64px);
}
.sbfx-calendar-header {
  width: 100%;
  padding: 20px;
  > li {
    height: 24px;
    cursor: pointer;
    > span {
      height: 24px;
      line-height: 24px;
    }
  }
}
.u-mlr10 {
  margin: 0 10px;
}
:deep(.el-calendar__body) {
  padding: 0;
  height: 100%;
  table {
    height: 100%;
  }
}
.sbfx-calendar :deep(.el-calendar) {
  // background-color: #161e35;
  height: 100%;
  flex-grow: 1;
  overflow-y: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+, edge */
  &::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
}
.sbfx-calendar :deep(.el-calendar .el-calendar__body .el-calendar-table thead th) {
  text-align: center;
}
.sbfx-calendar :deep(.el-calendar-table .el-calendar-day:hover),
.sbfx-calendar :deep(.el-calendar-table td.is-selected) {
  background-color: unset;
}
.sbfx-calendar :deep(.el-calendar-table .el-calendar-day) {
  height: 100%;
  padding: 0;
  color: #303133;
  font-size: 24px;
}
.sbfx-calendar :deep(.el-calendar__header) {
  padding: 0;
  border-bottom: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
.calendar-timeline :deep(.el-divider) {
  margin: 15px 0;
  background-color: rgba(0, 0, 0, 0.1);
}
:deep(.el-calendar-table) {
  td.next {
    pointer-events: none;
  }
  td.prev {
    pointer-events: none;
  }
}
.app-light {
  .calendar-timeline :deep(.el-timeline-item .el-timeline-item__wrapper .el-timeline-item__timestamp) {
    font-weight: bold;
    color: #303133;
  }
  :deep(.el-calendar .el-calendar__body .el-calendar-table thead th) {
    background-color: #dcdcdc;
    color: #606266;
    border: 1px solid #dcdcdc;
  }
  :deep(.el-calendar .el-calendar__body .el-calendar-table tbody td) {
    border-color: #dcdcdc;
  }
  :deep(.el-card) {
    background-color: #f9f9f9;
  }
}
.app-dark {
  .calendar-timeline :deep(.el-timeline-item .el-timeline-item__wrapper .el-timeline-item__timestamp) {
    font-weight: bold;
    color: #f5f5f5;
  }
  .calendar-timeline :deep(.el-timeline-item .el-timeline-item__tail) {
    border-color: rgba(255, 255, 255, 0.3);
  }
  :deep(.el-calendar .el-calendar__body .el-calendar-table thead th) {
    background-color: #2a3d5d;
    color: #c0c4cc;
    border: 1px solid #2a3d5d;
  }
  :deep(.el-calendar .el-calendar__body .el-calendar-table tbody td) {
    border-color: #30384d;
  }
  :deep(.el-form-item .el-card) {
    background-color: #1c2643;
  }
  :deep(.el-input__inner) {
    color: #e5eaf3;
  }
}
</style>
